function isString(something) {
  return typeof something === 'string';
}

function isFunction(something) {
  return typeof something === 'function';
}

function eventEmitter() {
  const events = {};
  let instance = null;

  // 监听事件
  function on(event, fn) {
    if (!isFunction(fn)) return instance;

    if (Array.isArray(event)) {
      event.forEach(e => on(e, fn));
    } else if (isString(event)) {
      (events[event] || (events[event] = [])).push(fn);
    }

    return instance;
  }

  // 取消监听事件
  function off(event, fn) {
    if (!isFunction(fn)) return instance;

    if (Array.isArray(event)) {
      event.forEach(e => off(e, fn));
    } else if (isString(event)) {
      if (events[event]) {
        events[event] = events[event].filter(f => f !== fn);
      }
    }

    return instance;
  }

  // 监听事件调用一次
  function once(event, fn) {
    if (!isFunction(fn)) return instance;

    function replaceFn(...rest) {
      off(event, replaceFn);
      fn(...rest);
    }

    on(event, replaceFn);
    return instance;
  }

  // 触发事件
  function emit(event, payload) {
    if (isString(event) && events[event]) {
      events[event].forEach(fn => fn(payload));
    }

    return instance;
  }

  instance = { on, once, off, emit };
  return instance;
}

const event = eventEmitter();

export { event, eventEmitter };
